<template>
	<el-tree :data="data" :props="defaultProps">
		<span class="custom-tree-node" slot-scope="{ node, data }">
			<span>{{ data.serviceName }},{{ data.ip }}:{{ data.port }},{{ data.uri }}</span>
			<span style="padding-left: 10px;">
				<el-button type="text" size="mini" @click="showParams(data)">查看详情</el-button>
				<el-link :underline="false" v-if="hasParams(data.params)" @click="showParams(data)">{{hasParams(data.params)}}个参数</el-link>
			</span>
		</span>
	</el-tree>
</template>

<script>
export default {
	props: {
		arr: {
			type: Array,
			default: () => []
		}
	},
	created() {
		this.initTree();
	},
	methods: {
		initTree() {
			let arr = this.arr.slice();
			let data = [];
			for (let i = 0; arr.length > 0; i++) {
				if (i > 10000) {
					console.warn('疑似出现无限循环');
					break;
				}
				//取出最左边的元素
				let item = arr.shift();
				if (item.caller) {
					//如果有caller
					let father = this.findFather(data, item.caller);
					// console.log(father)
					if (father) {
						//找到父级，直接设置
						let children = father.children;
						if (!children) {
							children = father.children = [];
						}
						children.push(item);
					} else {
						//如果没找到父级，放置队尾
						arr.push(item);
					}
				} else {
					data.push(item);
				}
			}
			this.data = data;
		},
		findFather(arr, name) {
			let obj = arr.find(item => {
				return item.serviceName + ':' + item.port === name;
			});
			if (obj) {
				return obj;
			} else {
				for (let item of arr) {
					if (item.children) {
						let node = this.findFather(item.children, name);
						if (node) {
							return node;
						}
					}
				}
				return null;
			}
		},
		showParams(data){
			console.log(data)
			this.$message.success("已打印在控制台")
		},
		hasParams(obj){
			let i=0
			for (let s in obj) {
				i++
			}
			return i
		}
	},
	data() {
		return {
			data: [],
			defaultProps: {
				children: 'children',
				label: 'label'
			}
		};
	}
};
</script>

<style></style>
